﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

[AddComponentMenu("Behavior/Timer")]
public class BhvTimer : MonoBehaviour
{

    public bool activeAtStart = true;
    [Tooltip("计时器的ID")]
    public string tid;
    [Tooltip("计时器目标循环次数，0 = 无限循环")]
    public int targetLoop = 0;

    private float curTime = 0;
    private float endTime = 0;

    public float targetTime = 2.0f;
    private int loopTime = 0;
    [Tooltip("目标时间随机偏移值")]
    public float targetTimeRandom = 0;
    public UnityEvent OnTimeEvents = new UnityEvent();

    public float CurTime { get => curTime; }
    public float LeftTime { get => endTime - curTime; }


    //计时器是否在运行中
    private bool _isRunning = false;
    public bool isRunning
    {
        get
        {
            return _isRunning;
        }
        private set
        {
            _isRunning = value;
        }
    }

    private void Awake()
    {
        if (activeAtStart)
        {
            StartTimer();
        }
    }

    public void DelayStartTimer(float delay, float interval)
    {
        StartCoroutine(_StartTimer(delay, interval));
    }

    private IEnumerator _StartTimer(float delay, float interval, int repeat = 1, float timeRnd = 0)
    {
        StartTimer(interval, repeat, timeRnd);
        this.isRunning = false;
        yield return new WaitForSeconds(delay);
        this.isRunning = true;
    }

    public void StartTimer()
    {
        loopTime = 0;
        this.isRunning = true;
        this.endTime = this.targetTime;
    }


    public void StartTimer(float interval, int repeat = 1, float timeRnd = 0)
    {
        //默认值不改变计时器的世界

        targetTime = interval;
        targetTimeRandom = timeRnd;
        targetLoop = repeat;
        StartTimer();

    }

    public void ResetTime()
    {
        curTime = 0;
    }

    public void StopTimer()
    {
        this.isRunning = false;
    }

    /// <summary>
    /// 获取当前计时器的进度
    /// </summary>
    public float GetProgress()
    {
        return this.curTime / this.targetTime;
    }

    private void OnFinishTimer()
    {
        curTime = 0;
        loopTime += 1;
        OnTimeEvents?.Invoke();
        if (this.targetLoop >= 1 && this.loopTime >= this.targetLoop)
        {
            StopTimer();
        }
        else
        {
            //随机变动目标时间
            if (this.targetTimeRandom != 0)
            {
                this.endTime = this.targetTime + (Random.Range(-1.0f, 1.0f)) * this.targetTimeRandom;
            }
            else
            {
                this.endTime = this.targetTime;
            }
        }

    }

    private void Update()
    {
        if (this.isRunning == false) return;
        if (this.enabled == false) return; //暂停时间

        this.curTime += Time.deltaTime;
        if (this.curTime >= this.endTime)
        {
            OnFinishTimer();
        }
    }




}
